#include "RecordManager.h"

// Reservar memoria para el vector de records
RecordManager::RecordManager() {
	_recordVector = new std::vector<Record>;
	_recordVector->reserve(MAXRECORDS + 1);
}

// Liberar memoria del vector de records y de la instancia del gestor
RecordManager::~RecordManager() {
	if (_recordVector)
		delete _recordVector;
	if (_recordManagerInstance)
		delete _recordManagerInstance;
}

RecordManager* RecordManager::_recordManagerInstance = NULL; // Singleton

// Singleton
RecordManager*
RecordManager::getRecordManager() {
	if (!_recordManagerInstance)
		_recordManagerInstance = new RecordManager;
	
	return _recordManagerInstance;
}

// Llenar el vector de records con el archivo indicado en la ruta
void
RecordManager::readRecords(const std::string& recordFilePath) {	
	std::ifstream recordFile;
	recordFile.open(recordFilePath.c_str(), std::ifstream::in);
	
	if (!recordFile.is_open()) return;
	
	Record record;
	
	if (_recordVector)
		_recordVector->clear();
	
	while (recordFile.good()) {
	
		recordFile >> record.name >> record.score;
		
		if (recordFile.good())
			_recordVector->push_back(record);
	}

	recordFile.close();
}

// Funcion para comparar dos records (la utiliza sort)
bool
RecordManager::compareRecord(Record r1, Record r2) {
	return r1.score > r2.score;
}

// Insertar un record
void
RecordManager::insertRecord(char* name, int score) {
	Record record;
	
	std::copy(name, name + MAXNAME + 1, record.name);
	record.score = score;

	_recordVector->push_back(record);
	
	// Ordenar el vector de records
	std::sort(
		_recordVector->begin(), 
		_recordVector->begin() + _recordVector->size(), 
		RecordManager::compareRecord
	);
	
	// Truncar si se tienen demasiados records
	if (_recordVector->size() > MAXRECORDS)
		_recordVector->pop_back();
}

// Obtener vector de records
std::vector<Record>*
RecordManager::getRecords() const {
	return _recordVector;
}

// Guardar records en el archivo indicado por la ruta pasada por argumento
void
RecordManager::writeRecords(const std::string& recordFilePath) {
	std::ofstream recordFile;
	recordFile.open(
		recordFilePath.c_str(), 
		std::ofstream::out | std::ofstream::trunc
	);
	
	std::vector<Record>::iterator it;
	
	for (it = _recordVector->begin(); it != _recordVector->end(); it++)
		recordFile << it->name << " " << it->score << "\n";
	
	recordFile.close();
}
		


